package wang.lcs.pay.config;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import com.github.wxpay.sdk.WXPayConfig;

@Configuration
@ConfigurationProperties(prefix = "app.weixin")
public class WeixinConfig implements WXPayConfig {

    private String notifyUrl;
    private String appID;
    private String mchID;
    private String key;
    private String certPath;
    private int httpConnectTimeoutMs = 8000;
    private int httpReadTimeoutMs = 10000;
    private boolean sandbox = false;

    private InputStream crer;

    public boolean isSandbox() {
        return sandbox;
    }

    public void setSandbox(boolean sandbox) {
        this.sandbox = sandbox;
    }

    public String getNotifyUrl() {
        return notifyUrl;
    }

    public void setNotifyUrl(String notifyUrl) {
        this.notifyUrl = notifyUrl;
    }

    public String getAppID() {
        return appID;
    }

    public void setAppID(String appID) {
        this.appID = appID;
    }

    public String getMchID() {
        return mchID;
    }

    public void setMchID(String mchID) {
        this.mchID = mchID;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getCertPath() {
        return certPath;
    }

    public void setCertFilePath(String certPath) {
        if (Files.isReadable(Paths.get(certPath))) {
            throw new RuntimeException("File not find Or Not to read !");
        }
        this.certPath = certPath;
    }

    public int getHttpConnectTimeoutMs() {
        return httpConnectTimeoutMs;
    }

    public void setHttpConnectTimeoutMs(int httpConnectTimeoutMs) {
        this.httpConnectTimeoutMs = httpConnectTimeoutMs;
    }

    public int getHttpReadTimeoutMs() {
        return httpReadTimeoutMs;
    }

    public void setHttpReadTimeoutMs(int httpReadTimeoutMs) {
        this.httpReadTimeoutMs = httpReadTimeoutMs;
    }

    @Override
    public InputStream getCertStream() {
        if (crer == null) {
            synchronized (this) {
                try {
                    crer = new ByteArrayInputStream(Files.readAllBytes(Paths.get(this.getCertPath())));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return crer;
    }

}